<template>
  <Dialog v-model="dialogVisible" :problemTitle="dialogTitle" width="70%">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="110px"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="门店封面" prop="coverImg">
            <UploadImg v-model="formData.coverImg" :limit="1" :is-show-tip="false" />
            <div style="font-size: 10px" class="pl-10px">推荐 180x180 图片分辨率</div>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="门店名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入门店名称" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="门店所在地区" prop="areaId">
            <el-cascader v-model="formData.areaId" :options="areaList" :props="defaultProps" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="门店地址" prop="detailAddress">
            <el-input
              type="textarea"
              :rows="3"
              v-model="formData.detailAddress"
              placeholder="请输入门店地址"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="营业时间" prop="openTime">
            <el-input v-model="formData.openTime" placeholder="请输入营业时间" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="每天可预约数量" prop="quota">
            <el-input-number
              v-model="formData.quota"
              :min="0"
              :precision="0"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="formData.phone" placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="获取经纬度">
            <el-button type="primary" @click="mapDialogVisible = true">获取</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="经度" prop="longitude">
            <el-input v-model="formData.longitude" placeholder="请输入门店经度" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="纬度" prop="latitude">
            <el-input v-model="formData.latitude" placeholder="请输入门店纬度" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <el-dialog v-model="mapDialogVisible" title="获取经纬度" append-to-body>
    <IFrame class="h-609px" :src="tencentLbsUrl" />
  </el-dialog>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getBoolDictOptions, getIntDictOptions } from '@/utils/dict'
import * as ArticleApi from '@/api/mall/promotion/article'
import * as shopApi from '@/api/service/shop/index'
import * as ConfigApi from '@/api/mall/trade/config'
import { getAreaTree } from '@/api/system/area'
import { defaultProps } from '@/utils/tree'

defineOptions({ name: 'ShopForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const categoryList = ref<any[]>([]) // 分类树
const mapDialogVisible = ref(false) // 地图弹窗的是否展示

const formData = ref({
  id: undefined,
  deviceTypeId: undefined,
  problemTitle: undefined,
  author: undefined,
  coverImg: undefined,
  introduction: undefined,
  latitude: undefined,
  longitude: undefined,
  areaId: undefined,
  detailAddress: '',
  name: '',
  quota: 100
})
const formRules = reactive({
  name: [{ required: true, message: '门店名称不能为空', trigger: 'blur' }],
  detailAddress: [{ required: true, message: '门店地址不能为空', trigger: 'blur' }],
  openTime: [{ required: true, message: '营业时间不能为空', trigger: 'blur' }],
  phone: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const areaList = ref() // 区域树
const tencentLbsUrl = ref('') // 腾讯位置服务 url
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  formData.value.videoUrl = ''
  if (id) {
    formLoading.value = true
    try {
      formData.value = await shopApi.getShop(id)
      formData.value.areaId = Number(formData.value.areaId)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ArticleApi.ArticleVO
    if (formType.value === 'create') {
      await shopApi.createShop(data)
      message.success(t('common.createSuccess'))
    } else {
      await shopApi.updateShop(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    introduction: undefined,
    sort: 0,
    status: 0,
    quota: 100
  }
  formRef.value?.resetFields()
}

/** 选择经纬度 */
const selectAddress = function (loc: any): void {
  if (loc.latlng && loc.latlng.lat) {
    formData.value.latitude = loc.latlng.lat
  }
  if (loc.latlng && loc.latlng.lng) {
    formData.value.longitude = loc.latlng.lng
  }
  mapDialogVisible.value = false
}

/** 初始化腾讯地图 */
const initTencentLbsMap = async () => {
  window.selectAddress = selectAddress
  window.addEventListener(
    'message',
    function (event) {
      // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
      let loc = event.data
      if (loc && loc.module === 'locationPicker') {
        // 防止其他应用也会向该页面 post 信息，需判断 module 是否为 'locationPicker'
        window.parent.selectAddress(loc)
      }
    },
    false
  )
  const data = await ConfigApi.getTradeConfig()
  const key = data.tencentLbsKey
  tencentLbsUrl.value = `https://apis.map.qq.com/tools/locpicker?type=1&key=${key}&referer=myapp`
}

onMounted(async () => {
  areaList.value = await getAreaTree()
  // 加载地图
  await initTencentLbsMap()
})
</script>
